<template>
	<view class="scan">
		<!-- 头部 -->
		<view class="header">
			<view class="headerTitle">
				<text>当前桌位</text>
				<text style="color: rgb(230,203,23);margin:0 10rpx;font-size: 35rpx;">{{ tableSeat }}</text>
				<text>{{oldOrderMsg.dinnerNum ? oldOrderMsg.dinnerNum : seatValue}}人</text>
			</view>
			<view class="search">
				<u-search 
					:clearabled="true" 
					shape="round"
					:showAction="false"
					bgColor="#000000">
				</u-search>
			</view>
		</view>
		
		<!-- 内容 -->
		<view class="foodContent" style="background-image: url('/static/scan/bg.jpg');">
			<view :class="{'sider':true, 'show':classifyShow, 'hide':!classifyShow}">
				<view
					:class="{ 'sider-item':true, 'is-active':currentId === 'recommend' }"
					@tap="currentId = 'recommend'">
					推荐
				</view>
				<view
					v-for="(item, index) in classifyData"
					:key="item.id"
					:class="{ 'sider-item':true, 'is-active':item.id === currentId }"
					@tap="currentId = item.id">
					{{ item.name }}
				</view>
			</view>
			<!-- 右边菜品 -->
			<view class="b-right">
				<view :class="{'closeClassify':true, 'show-card':classifyShow, 'hide-card':!classifyShow}" @click="closeClassify">
					<text>{{colseText}}</text>
					<u-icon :name="classifyShow ? 'arrow-left' : 'arrow-right'" size="13" bold="true" color="#ed283f"></u-icon>
				</view>
				<scroll-view scroll-y="true" class="content" scroll-with-animation :scroll-into-view="'id' + currentId">
					<!-- 推荐菜品 -->
					<view id="idrecommend" class="bigCard">
						<view class="r-title">
							上新菜品
						</view>
						<view v-for="(item, index) in recommendFoodData" :key="item.id" class="r-Image">
							<image class="img" :src="item.image" @click="toFoodDetail(item.id)"></image>
							<view class="name">
								{{item.name}}
							</view>
							<view class="price">
								{{item.sprice}}
							</view>
							<view v-if="getSum(item)" class="calculate">
								<u-icon name="minus-circle" color="#ff0000" size="22"></u-icon>
								<text style="margin: 10rpx;">{{ getSum(item) }}</text>
								<u-icon name="plus-circle-fill" color="#ff0000" size="22" @click="getSpecData(item)"></u-icon>
							</view>
							<view v-else class="addbig-icon" @click="getSpecData(item)">
								<u-icon name="plus-circle-fill" color="#ff0000" size="30"></u-icon>
							</view>
						</view>
					</view>
					
					<!-- 正常菜品 -->
					<view :id="'id' + item.id" class="food" 
						v-for="item in foodList" 
						:key="item.id">
						<text class="foodTitle">{{ item.name }}</text>
						<view class="food-box">
							<view class="foodCard" v-for="food in item.foods" :key="food.id"  >
								<view class="card-top" @click="toFoodDetail(food.id)">
									<image class="foodImage" mode="scaleToFill" :src="foodImage(food.image)"></image>
									<view class="foodPrice">
										￥<span style="font-weight: bold;">{{ food.sprice }}</span>
									</view>
								</view>
								<view class="foodText">{{ food.name }}</view>
								<view v-if="food.num" class="calculate">
									<u-icon name="minus-circle" color="#ff0000" size="22" @click="getSpecData(food)"></u-icon>
									<text style="margin: 10rpx;">{{food.num}}</text>
									<u-icon name="plus-circle-fill" color="#ff0000" size="22" @click="getSpecData(food)"></u-icon>
								</view>
								<view v-else class="add-icon">
									<u-icon name="plus-circle-fill" color="#ff0000" size="20" @click="getSpecData(food)"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		
		<!-- 菜品弹窗 -->
		<food-specification
			v-if="specShow"
			:show.sync="specShow"
			:specData="specData"
			:currentFood="currentFood"
			@plusFood="plusFood"
			@plusNum="plusNum"
			@subtractNum="subtractNum"
		/>
		
		<!-- 我的 -->
		<view class="me" @click="toMe">
			<u-avatar icon="star-fill" fontSize="15" size="25"></u-avatar>
			<text class="meText">我的</text>
		</view>
		
		<!-- 购物车弹窗 -->
		<view class="order" @click="show = true">
			<u-icon name="shopping-cart-fill" color="#ffffff" size="40"></u-icon>
			<text>购物车</text>
			<view class="badge" v-if="sum != 0">
				{{ sum }}
			</view>
		</view>
		
		<!-- 购物车弹窗 -->
		<view class="shopping">
			<u-popup
				:show="show"
				mode="bottom"
				@close="close"
				:round="15"
				:closeOnClickOverlay="true"
				:customStyle="{'max-height':'70vh'}">
				<view class="shopCarTitle">
					<view class="selected">
						<text>已选商品</text>
						<text style="font-size: 25rpx;color: red;margin-left: 10rpx;">(共{{sum}}件商品，总计{{ totalMoney }}元)</text>
					</view>
					<view class="trash" v-if="sum != 0" @click="trashShop">
						<u-icon name="trash" size="18"></u-icon>
						<view>清空购物车</view>
					</view>
				</view>
				<view class="choose-food-box">
					<view v-for="food in shopData" :key="food.id">
						<view class="chooseFood" v-for="item in food.specs" :key="item.id">
							<image class="foodImage" :src="food.image"></image>
							<view class="foodMessage">
								<view style="font-size: 30rpx;font-weight: bold;">{{food.name}}</view>
								<view style="font-size: 22rpx;color: #A9A9A9;">{{item.size}}</view>
								<view style="font-size: 25rpx;color: #ff0000;">￥{{item.price}}</view>
							</view>
							<view class="calculate">
								<u-icon name="minus-circle" color="#ff0000" size="22" @click="subtractNum(food, item)"></u-icon>
								<text style="margin: 10rpx;">{{item.num}}</text>
								<u-icon name="plus-circle-fill" color="#ff0000" size="22" @click="plusNum(food, item)"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="toOrder" @click="toPlaceOrder" v-if="sum != 0">
					<text>去下单</text>
				</view>
				<view v-else style="margin: 0 auto;padding: 60rpx 0;">
					<text>购物车里面还没有菜品哦~</text>
				</view>
			</u-popup>
		</view>
		
		<!-- 选座位弹窗 -->
		<view class="chooseSeat">
			<u-popup
				:show="seatShow" 
				mode="center" 
				@close="seatClose"
				:round="10">
				<view class="seat">
					<text class="title">选择用餐人数</text>
					<view class="peopleSeat">
						<view class="peopleNumber">
							<view class="seatItem" 
								v-for="item in 12" 
								@click="seatValue = item+1"
								:class="{ 'active': item === currentSeatId }"
								@tap="chooseSeat(item)">
								{{item+1}}
							</view>
						</view>
					</view>
					<view class="personalSeat">
						<text>输入人数: </text>
						<u--input
							placeholder="请输入内容"
							border="surround"
							v-model="seatValue"
							:customStyle="{'padding': '0 9px'}"
						></u--input>
					</view>
					<view class="startOrder">
						<u-button 
							@click="start"
							type="primary" 
							text="开始点餐" 
							color="#ff0000" 
							:customStyle="{ 'width': '350rpx', 'height': '60rpx', 'margin-top': '30rpx', 'border-radius': '50rpx'}">
						</u-button>
					</view>
				</view>
			</u-popup>
		</view>
		
	</view>
</template>

<script>
// import { , BusinessDetail, byUserId_OrderDetail, byUserIdMessage } from '@/common/http.api.js'
import { LOGIN, get_classify, get_classifyFood, Food_List, foodSpecification, addOrder, specAdd, byUserId_OrderDetail, editOrder } from '@/common/http.api.js'
import store from '@/store/index.js'
import { FoodSpecification } from '@/component/foodSpecification/foodSpecification.vue'
export default {
	components: { FoodSpecification },
	data() {
		return {
			src: 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg',
			colseText:'关闭分类',
			currentId: 'recommend',
			currentSeatId: 0,
			classifyData:[],
			classifyShow:true,
			isShow: true,
			getByClassifyFood:[],
			foodList:[],
			recommendFoodData:[],
			title:'标题',
			show: false,
			seatShow:false,
			specShow:false,
			sumNum:0,
			shopData:this.$store.state.shopData,
			seatValue:'',
			tableSeat: '',
			specData:[],
			currentFood: {},
			userId: this.$store.state.userId,
			oldOrderMsg: {}
		}
	},
	onLoad(option){
		this.tableSeat = option.tableSeat
		this.init()
	},
	methods:{
		init() {
			Promise.all([ get_classify(), Food_List() ]).then( res => {
				this.classifyData = res[0].rows
				let foodData = res[1].rows
				foodData = foodData.filter( item => {
					return item.status == 0
				})
				const classifyObj = {}
				this.classifyData.forEach( item => {
					item.foods = []
					classifyObj[item.id] = item
				})
				if (this.shopData.length > 0) {
					let length = 0
					foodData = foodData.map( listFood => {
						if (length !== this.shopData.length) {
							const index = this.shopData.findIndex( shopFood => shopFood.id === listFood.id)
							if (index >= 0) {
								length++
								return this.shopData[index]
							}
						}
						return listFood
					})
				}
				foodData.forEach( item => {
					classifyObj[item.classifyId].foods.push(item)
				})
				this.foodList = Object.values(classifyObj)
				this.recommendFoodData = foodData.filter((item, index) => {
					return item.isRecommend == 0 && item.status == 0
				})
			})
			//拿到用户所有的订单
			byUserId_OrderDetail(this.userId).then( res => {
				for (let i=0; i<res.rows.length; i++) {
					if(res.rows[i].currentStatus == '未支付') {
						this.oldOrderMsg = res.rows[i]
						return
					}
				}
				this.seatShow = true;
			})
		},
		// 获取某个菜品已加入购物车的数量
		getSum(food) {
			const index = this.shopData.findIndex( item => item.id === food.id)
			if (index >= 0) {
				let sum = 0
				this.shopData[index].specs.forEach( item => {
					sum += item.num
				})
				return sum
			}
			return 0
		},
		close() {
		  this.show = false
		},
		chooseSeat(item){
			this.currentSeatId = item
		},
		seatClose(){
			this.seatShow = false
		},
		closeClassify(){
			this.classifyShow = !this.classifyShow
			if(this.classifyShow){
				this.colseText = '关闭分类'
			}else{
				this.colseText = '展开分类'
			}
		},
		// 返回第一张图片
		foodImage(image){
			const imageItem = image.split(',')
			return imageItem[0]
		},
		//去菜品详情
		toFoodDetail(id){
			uni.navigateTo({
				url: `/pagesA/home/foodDetail/foodDetail?id=${id}`
			}) 
		},
		// 去下单
		toPlaceOrder(){
			let time = Date.now()
			if(this.oldOrderMsg.id){
				let eidtOrder = {
					id: this.oldOrderMsg.id,
					totalPrice: parseFloat(this.oldOrderMsg.totalPrice) + this.totalMoney,
					currentStatus: '未支付'
				}
				editOrder(eidtOrder).then( res => {
					const requestArr = []
					this.shopData.forEach( food => {
						food.specs.forEach( spec => {
							requestArr.push( specAdd({
									orderId: this.oldOrderMsg.id,
									specificationId: spec.id,
									number: spec.num,
									price: spec.price
							}))
						})
					})
					Promise.all(requestArr).then( resp => {
						this.shopData = []
						this.$store.commit('SET_SHOP', [])
						uni.removeStorageSync("scancode")
						uni.navigateTo({
							url: `/pagesA/home/placeOrder/placeOrder?orderId=${this.oldOrderMsg.id}`
						})
					}).catch( err => {
						uni.showToast({
							icon: 'error',
							text: err
						})
					})
				})
			}else{
				const orderFrom = {
					userId : this.userId,
					totalPrice : this.totalMoney,
					dinnerNum : this.seatValue,
					tableNum : this.tableSeat
				}
				addOrder(orderFrom).then( res => {
					const requestArr = []
					this.shopData.forEach( food => {
						food.specs.forEach( spec => {
							requestArr.push( specAdd({
								orderId: res.msg,
								specificationId: spec.id,
								number: spec.num,
								price: spec.price
							}))
						})
					})
					// console.log(requestArr)
					Promise.all(requestArr).then( resp => {
						this.shopData = []
						this.$store.commit('SET_SHOP', [])
						uni.removeStorageSync("scancode")
						uni.navigateTo({
							url: `/pagesA/home/placeOrder/placeOrder?orderId=${res.msg}`
						})
					}).catch( err => {
						uni.showToast({
							icon: 'error',
							text: err
						})
					})
				})
			}
		},
		// 获取规格
		getSpecData(food){
			foodSpecification(food.id).then( res => {
				let specData = [ ...res.rows ]
				const index = this.shopData.findIndex( item => item.id === food.id)
				if (index >= 0) {
					specData = specData.map( spec => {
						for (let i=0; i<this.shopData[index].specs.length; i++) {
							if (spec.id === this.shopData[index].specs[i].id) {
								return this.shopData[index].specs[i]
							}
						}
						return spec
					})
				}
				this.currentFood = food
				this.specData = specData
				this.specShow = true
			})
		},
		plusFood(food, spec) {
			// const foodData = { ...food }, specData = { ...spec }
			const specIndex = this.specData.findIndex( item => item.id === spec.id)
			this.$set(this.specData[specIndex], 'num', 1)
			const index = this.shopData.findIndex( item => item.id === food.id)
			if (index >= 0) {
				this.shopData[index].specs.push(this.specData[specIndex])
			} else {
				food.specs = [ this.specData[specIndex] ]
				this.shopData.push(food)
			}
			this.$store.commit('SET_SHOP', this.shopData)
			uni.setStorageSync('scancode', JSON.stringify(this.shopData))
		},
		//加1
		plusNum(food, spec){
			const foodIndex = this.shopData.findIndex( item => item.id === food.id)
			const specIndex = this.shopData[foodIndex].specs.findIndex( item => item.id === spec.id)
			this.shopData[foodIndex].specs[specIndex].num++
			this.$store.commit('SET_SHOP', this.shopData)
			uni.setStorageSync('scancode', JSON.stringify(this.shopData))
		},
		//减1
		subtractNum(food, spec){
			const foodIndex = this.shopData.findIndex( item => item.id === food.id)
			const specIndex = this.shopData[foodIndex].specs.findIndex( item => item.id === spec.id)
			if (spec.num === 1) {
				this.shopData[foodIndex].specs[specIndex].num--
				if (this.shopData[foodIndex].specs.length === 1) {
					this.shopData.splice(foodIndex, 1)
				} else {
					this.shopData[foodIndex].specs.splice(specIndex, 1)
				}
			} else {
				this.shopData[foodIndex].specs[specIndex].num--
			}
			this.$store.commit('SET_SHOP', this.shopData)
			uni.setStorageSync('scancode', JSON.stringify(this.shopData))
		},
		//清理购物车
		trashShop(){
			this.shopData = []
			this.$store.commit('SET_SHOP', this.shopData)
			uni.setStorageSync('scancode', JSON.stringify(this.shopData))
		},
		start(){
			this.seatShow = false
		},
		
		//去我的页面
		toMe(){
			console.log('1111')
			uni.switchTab({
				url: `/pages/me/me`
			})
		}
	},
	computed: {
		sum() {
			if (this.shopData.length === 0) {
				return 0
			} else {
				let sum = 0
				this.shopData.forEach( food => {
					food.specs.forEach( item => {
						sum += item.num
					})
				})
				return sum
			}
		},
		//总计
		totalMoney(){
			if (this.shopData.length === 0) {
				return 0
			}else{
				let money = 0
				this.shopData.forEach( food => {
					food.specs.forEach( item => {
						money += item.num * parseFloat(item.price)
					})
				})
				return money
			}
		}
	}
}
</script>

<style lang="less" scoped>
.scan{
	display: flex;
	flex-direction: column;
	width: 100vw;
	height: 100vh;
	box-sizing: border-box;
	.header{
		
		.headerTitle{
			height: 50rpx;
			background-color: #000000;
			color: #ffffff;
			line-height: 30rpx;
			text-align: center;
			font-size: 26rpx;
		}
		.search{
			background-color: #000000;
		}
	}
	.foodContent{
		flex: 1;
		display: flex;
		overflow: hidden;
		.sider {
			height: 100%;
			overflow-y: auto;
			background-color: rgb(211,211,211);
			transition: width 0.25s;
			.sider-item {
				padding: 45rpx 8rpx;
				font-size: 28rpx;
				font-family:"Microsoft YaHei";
				text-align: center;
				color: #5c5b5b;
			}
			.is-active {
				color: rgb(239,204,40);
				background-color: rgb(63,61,49);
			}
		}
		.show {
			width: 136rpx;
		}
		.hide {
			width: 0;
		}
		.b-right {
			flex: 1;
			position: relative;
			padding: 10rpx;
			overflow-y: auto;
			.closeClassify{
				position: fixed;
				top: 50%;
				transform: translateY(-50%);
				padding: 15rpx;
				font-size: 22rpx;
				border-top-right-radius: 20rpx;
				border-bottom-right-radius: 20rpx;
				background-color: rgb(211,211,211);
				z-index: 2;
				transition: left 0.25s;
				text {
					writing-mode: tb-rl;
					letter-spacing: 5rpx;
				}
			}
			.show-card {
				left: 136rpx;
			}
			.hide-card {
				left: 0;
			}
			
			.content {
				width: 100%;
				height: 100%;
				.bigCard{
					margin: 10rpx;
					.r-title{
						color:#ffffff;
						font-size: 40rpx;
						font-family:"Microsoft YaHei";
					}
					.r-Image{
						margin-top: 25rpx;
						width: 100%;
						height: 520rpx;
						padding: 10rpx;
						position: relative;
						border-radius: 25rpx;
						box-sizing: border-box;
						background-color: rgb(207,206,205);
						.img{
							width: 100%;
							height: 400rpx;
							border-radius: 25rpx;
						}
						.name{
							font-size: 30rpx;
						}
						.price{
							width: 200rpx;
							height: 60rpx;
							border-top-left-radius: 50rpx;
							border-bottom-right-radius: 25rpx;
							position: absolute;
							right: 9rpx;
							bottom: 110rpx;
							text-align: center;
							line-height: 60rpx;
							background-color: rgb(236,237,231);
							font-family:"Microsoft YaHei";
						}
						.addbig-icon {
							flex: 1;
							display: flex;
							justify-content: flex-end;
							align-items: flex-end;
							width: 100%;
						}
					}
					.calculate {
						display: flex;
						justify-content: flex-end;
					}
				}
				.food{
					.foodTitle{
						margin: 15rpx 0;
						font-size: 40rpx;
						font-family:"Microsoft YaHei";
						color: #ffffff;
					}
					.food-box {
						display: flex;
						flex-wrap: wrap;
						.foodCard{
							display: flex;
							flex-direction: column;
							margin: 20rpx 10rpx;
							padding: 8rpx;
							width: calc(33.33% - 20rpx);
							color: #5c5b5b;
							background-color: rgb(207,206,205);
							border-radius: 15rpx;
							box-sizing: border-box;
							.card-top {
								width: 100%;
								position: relative;
								.foodImage{
									width: 100%;
									height: 180rpx;
									border-radius: 15rpx;
								}
								.foodPrice{
									position: absolute;
									bottom: 8rpx;
									right: 0;
									padding: 8rpx;
									font-size: 24rpx;
									border-top-left-radius: 30rpx;
									border-bottom-right-radius: 15rpx;
									background-color: rgb(236,237,231);
								}
							}
							.foodText{
								font-size: 28rpx;
								font-family:"Microsoft YaHei";
							}
							.add-icon {
								flex: 1;
								display: flex;
								justify-content: flex-end;
								align-items: flex-end;
								width: 100%;
							}
							.calculate {
								display: flex;
								justify-content: flex-end;
							}
						}
					}
				}
			}
		}
	}
		
	.order{
			color: #ffffff;
			font-size: 25rpx;
			text-align: center;
			position: fixed;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 120rpx;
			height: 120rpx;
			font-weight: bold;
			background-image: linear-gradient(30deg,rgb(240,65,93),rgb(249,78,35));
			border-radius: 50%;
			border: 3px solid #ffffff;
			right: 30rpx;
			bottom: 30rpx;
			.badge{
				position: absolute;
				width: 35rpx;
				height: 35rpx;
				border-radius: 50%;
				color: #ffffff;
				font-size: 30rpx;
				background-color: #ff0000;
				left: -5rpx;
				top: -5rpx;
				padding: 5rpx;
				text-align: center;
				line-height: 35rpx;
			}
		}
	
	.me{
		display: flex;
		color: #ffffff;
		border-left: 50%;
		position: absolute;
		background-color: rgba(0, 0, 0, 0.2);
		padding: 10rpx;
		align-items: center;
		border-left: 1px solid rgb(105,105,105);
		border-top: 1px solid rgb(105,105,105);
		border-bottom: 1px solid rgb(105,105,105);
		border-top-left-radius: 50rpx;
		border-bottom-left-radius: 50rpx;
		right: 0;
		top: 150rpx;
		.meText{
			margin-left: 10rpx;
		}
	}
	
	.shopping{
		display: flex;
		flex-direction: column;
		.shopCarTitle{
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx;
			height: 50rpx;
			border-bottom: 1px solid #F5F5F5;
			.selected{
				flex: 1;
				font-size: 30rpx;
			}
			.trash{
				display: flex;
				font-size: 25rpx;
				align-items: center;
			}
		}
		.choose-food-box {
			flex: 1;
			overflow-y: auto;
			.chooseFood{
				display: flex;
				padding: 10rpx;
				// margin-top: 20rpx;
				align-items: center;
				border-bottom: 1px solid #F5F5F5;
				.foodImage{
					width: 120rpx;
					height: 120rpx;
				}
				.foodMessage{
					flex: 1;
					margin: 15rpx;
					line-height: 40rpx;
				}
				.calculate{
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
		.toOrder{
			padding: 20rpx;
			width: 100%;
			text-align: right;
			box-sizing: border-box;
			text {
				padding: 10rpx 30rpx;
				background-color: #ff0000;
				color: #ffffff;
				font-size: 30rpx;
				border-radius: 50rpx;
			}
		}
	}
	
	.chooseSeat{
		.seat{
			padding: 5rpx;
			width: 550rpx;
			height: 500rpx;
			.title{
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: bold;
				margin-top: 30rpx;
			}
			.peopleSeat{
				width: 100%;
				height: 55%;
				display: flex;
				align-items: center;
				justify-content: center;
				.peopleNumber{
					display: flex;
					flex-wrap: wrap;
					justify-content: space-around;
					align-content: space-around;
					.seatItem{
						width: 90rpx;
						height: 50rpx;
						margin: 10rpx;
						text-align: center;
						border: 1px solid #DCDCDC;
					}
					.active{
						color: #ffffff;
						background-color: rgba(255,0,0,0.8);
					}
				}
			}
			.personalSeat{
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 0 10%;
				text {
					margin-right: 20rpx;
				}
			}
		}
	}
	
}
</style>
